package controllers

import (
	"ai/models"
	"ai/services"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	faceid "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/faceid/v20180301"
	vrs "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/vrs/v20200824"
	"time"
)

type ApiController struct {
	logService services.LogService
}

func NewApiController(logService services.LogService) *ApiController {
	return &ApiController{logService: logService}
}

type Response struct {
	Data      map[string]interface{} `json:"Data"`
	RequestId string                 `json:"RequestId"`
}

type ApiResponse struct {
	Response Response `json:"Response"`
}

type ApiResponse1 struct {
	Response struct {
		Result      string `json:"Result"`
		Description string `json:"Description"`
		RequestId   string `json:"RequestId"`
	} `json:"Response"`
}

func GetTrainingText(c *gin.Context) {
	credential := common.NewCredential(
		"AKIDpW1Lfu265tTp16yiJkx2zjHdlfMp6EE1",
		"d1FG3dz7HJ8oLivxkKhssetAF7lBPSKh",
	)
	// 实例化一个client选项，可选的，没有特殊需求可以跳过
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "vrs.tencentcloudapi.com"
	// 实例化要请求产品的client对象,clientProfile是可选的
	client, _ := vrs.NewClient(credential, "ap-guangzhou", cpf)

	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := vrs.NewGetTrainingTextRequest()

	request.TaskType = common.Int64Ptr(5)

	// 返回的resp是一个GetTrainingTextResponse的实例，与请求对象对应
	responses, err := client.GetTrainingText(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		fmt.Printf("An API error has returned: %s", err)
		return
	}
	if err != nil {
		panic(err)
	}
	result := responses.ToJsonString()
	// 输出json格式的字符串回包
	//fmt.Printf("%s", result)
	var response ApiResponse
	err = json.Unmarshal([]byte(result), &response)
	if err != nil {
		fmt.Println("JSON unmarshaling failed:", err)
		return
	}
	// 返回成功响应
	c.JSON(200, gin.H{"code": 1, "msg": "success", "data": response.Response.Data})
}

func (api *ApiController) DetectEnvAndSoundQuality(c *gin.Context) {
	aid := c.PostForm("aid")
	mid := c.PostForm("mid")
	textId := c.PostForm("textId")
	audioData := c.PostForm("audioData")

	credential := common.NewCredential(
		"AKIDpW1Lfu265tTp16yiJkx2zjHdlfMp6EE1",
		"d1FG3dz7HJ8oLivxkKhssetAF7lBPSKh",
	)
	// 实例化一个client选项，可选的，没有特殊需求可以跳过
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "vrs.tencentcloudapi.com"
	// 实例化要请求产品的client对象,clientProfile是可选的
	client, _ := vrs.NewClient(credential, "", cpf)

	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := vrs.NewDetectEnvAndSoundQualityRequest()

	request.TextId = common.StringPtr(textId)
	request.AudioData = common.StringPtr(audioData)
	request.TypeId = common.Int64Ptr(2)
	request.TaskType = common.Int64Ptr(5)

	// 返回的resp是一个DetectEnvAndSoundQualityResponse的实例，与请求对象对应
	responses, err := client.DetectEnvAndSoundQuality(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		fmt.Printf("An API error has returned: %s", err)
		return
	}
	if err != nil {
		panic(err)
	}
	result := responses.ToJsonString()
	var response ApiResponse
	err = json.Unmarshal([]byte(result), &response)
	if err != nil {
		fmt.Println("error", err)
		return
	}
	data := response.Response.Data
	jsonData, err := json.Marshal(data)
	if err != nil {
		fmt.Println("JSON marshaling failed:", err)
		return
	}
	log := models.ApiLog{
		Aid:        parseInt(aid),
		Mid:        parseInt(mid),
		Param:      textId,
		Content:    string(jsonData),
		Channel:    "DetectEnvAndSoundQuality",
		CreateTime: time.Now().Format("2006-01-02 15:04:05"),
	}

	if err := api.logService.CreateLog(&log); err != nil {
		c.JSON(500, gin.H{"error": "Failed to create log"})
		return
	}

	if data["DetectionCode"] != 0 {
		c.JSON(200, gin.H{"code": 0, "msg": "未获取到数据", "data": ""})
		return
	}
	// 返回成功响应
	c.JSON(200, gin.H{"code": 1, "msg": "success", "data": data})
}

func (api *ApiController) IdCardVerification(c *gin.Context) {
	idCard := c.PostForm("idCard")
	name := c.PostForm("name")

	credential := common.NewCredential(
		"AKIDpW1Lfu265tTp16yiJkx2zjHdlfMp6EE1",
		"d1FG3dz7HJ8oLivxkKhssetAF7lBPSKh"+
			"",
	)
	// 实例化一个client选项，可选的，没有特殊需求可以跳过
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "faceid.tencentcloudapi.com"
	// 实例化要请求产品的client对象,clientProfile是可选的
	client, _ := faceid.NewClient(credential, "", cpf)

	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := faceid.NewIdCardVerificationRequest()

	request.IdCard = common.StringPtr(idCard)
	request.Name = common.StringPtr(name)
	// 返回的resp是一个IdCardVerificationResponse的实例，与请求对象对应
	responses, err := client.IdCardVerification(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		fmt.Printf("An API error has returned: %s", err)
		return
	}
	if err != nil {
		panic(err)
	}
	result := responses.ToJsonString()
	fmt.Printf("%s", responses.ToJsonString())

	var resp ApiResponse1
	err = json.Unmarshal([]byte(result), &resp)
	if err != nil {
		fmt.Println("解析出错:", err)
		return
	}

	if resp.Response.Result != "0" {
		c.JSON(200, gin.H{"code": 0, "msg": resp.Response.Description, "data": ""})
		return
	}
	c.JSON(200, gin.H{"code": 1, "msg": resp.Response.Description, "data": ""})
}
